package com.eep.shipping;

import com.eep.common.PropertyReader;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;

/**
 * This class implements the business delegate pattern and allows business
 * logic to be evaluated through a simple POJO that implements an interface.
 *
 * Business Delegate Pattern:
 * http://java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html
 *
 */
public class ShippingServiceDelegate {

    private ShippingService shippingService;
    /**
     * Property key constants
     */
    private static String SHIP_DEL_AS_EJB = "shippingDelegateAsEJB";
    private static String SHIP_DEL_EJB_PROVIDER_URL = "shippingDelegateEJBProviderUrl";
    private static String SHIP_DEL_EJB_INITIAL_CONTEXT = "shippingDelegateEJBInitialContext";
    private static String SHIP_DEL_EJB_NAME = "shippingDelegateEJBName";
    private static String SHIP_DEL_LOCAL_CLASS_NAME = "shippingDelegateLocalClassName";

    /**
     * Creates the business delegate that provides access to an implementation
     * of the InventoryService.  The business delegate hides the creation
     * details of the interface and allows the business delegate to connect
     * to local or remote session contexts.
     */
    public ShippingServiceDelegate() {

        PropertyReader prop = PropertyReader.getInstance();

        boolean isEjb = Boolean.parseBoolean(String.valueOf(prop.getBoolean(SHIP_DEL_AS_EJB)));
        try {
            if (isEjb) {
                // Create a remote instance of this interface
                Hashtable env = new Hashtable();
                String providerUrl = prop.getString(SHIP_DEL_EJB_PROVIDER_URL);
                String initialContextStr = prop.getString(SHIP_DEL_EJB_INITIAL_CONTEXT);
                String ejbName = prop.getString(SHIP_DEL_EJB_NAME);
                env.put(Context.PROVIDER_URL, providerUrl);
                env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextStr);
                Context initialContext = new InitialContext(env);
                shippingService = ShippingService.class.cast(initialContext.lookup(ejbName));
            } else {
                // Create a local instance of this interface
                String className = prop.getString(SHIP_DEL_LOCAL_CLASS_NAME);
                shippingService = ShippingService.class.cast(Class.forName(className).newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public ShippingService getShippingService() {
        return shippingService;
    }
}
